<?php
//卸载插件
function baidu_submit_uninstall() {
    delete_option('baidu_submit_auto');
    delete_option('baidu_submit_key');
}

//推送到百度
function baidu_submit_send($urls) {
    $api_key = get_option('baidu_submit_key');
    if(!$api_key) return;

    $site_url = get_option('siteurl');
    $api = 'http://data.zz.baidu.com/urls?site=' . $site_url . '&token=' . $api_key;

    $response = wp_remote_post($api, [
        'sslverify' => isset($_SERVER['HTTPS']) && 'on' == $_SERVER['HTTPS'] ? true : false,
        'headers' => [
            'Content-Type' => 'text/plain',
        ],
        'body' => $urls
    ]);

    if(is_wp_error($response)) {
        return $response->get_error_message();
    }

    $data = json_decode(wp_remote_retrieve_body($response));
    if(!isset($data->success)) {
        return $data->message;
    } else {
        return $data->success;
    }
}

//发布文章自动推送
function baidu_submit_insert_post($post_id, $post, $update) {
    if($update || $post->post_status != 'publish' || $post->post_type != 'post' || !get_option('baidu_submit_auto')) return;

    $url = get_permalink($post_id);
    baidu_submit_send($url);
}
add_action('wp_insert_post', 'baidu_submit_insert_post', 10, 3);
?>